package com.gaoyi.crm.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.gaoyi.crm.R;
import com.gaoyi.crm.apiresult.ApiResultData;
import com.gaoyi.crm.callback.OnResultListener;
import com.gaoyi.crm.callback.OnSyncListener;
import com.gaoyi.crm.constant.ApiStatus;
import com.gaoyi.crm.db.bean.ResultBean;
import com.gaoyi.crm.db.entity.Category;
import com.gaoyi.crm.db.entity.ItemNoStore;
import com.gaoyi.crm.db.entity.Pmn;
import com.gaoyi.crm.db.entity.PmnAttach;
import com.gaoyi.crm.db.entity.PmnItemNo;
import com.gaoyi.crm.db.entity.PmnWithList;
import com.gaoyi.crm.fragment.ScannedListFragment;
import com.gaoyi.crm.repository.ItemNoStoreRepository;
import com.gaoyi.crm.repository.NewPmnRepository;
import com.gaoyi.crm.repository.PmnItemNoRepository;
import com.gaoyi.crm.repository.PmnRepository;
import com.gaoyi.crm.repository.SyncRepository;
import com.gaoyi.crm.util.StringUtil;
import com.gaoyi.crm.util.SyncUploadUtil;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.util.Utils;
import com.gaoyi.crm.vm.base.BaseListViewModel;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ScannedListViewModel extends BaseListViewModel<ItemNoStore> {

    final SyncRepository mSync;
    final ItemNoStoreRepository mRepository;
    final NewPmnRepository mNewPmn;
    final PmnItemNoRepository mPmnItemNo;
    final PmnRepository mPmn;
    MutableLiveData<ResultBean> mResult;

    public MutableLiveData<ResultBean> getResult() {
        if (mResult == null) {
            mResult = new MutableLiveData<>();
        }
        return mResult;
    }

    public ScannedListViewModel(@NonNull Application application) {
        super(application);
        mRepository = new ItemNoStoreRepository();
        mNewPmn = new NewPmnRepository();
        mPmnItemNo = new PmnItemNoRepository();
        mSync = new SyncRepository();
        mPmn = new PmnRepository();
    }

    public void getItemNoStore(String itemNo) {
        if (getView() != null) {
            getView().showLoading();
        }
        mRepository.getItemNo(itemNo, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                ApiResultData<ItemNoStore> apiResultData = (ApiResultData<ItemNoStore>) apiResult;
                if (apiResultData.getStatus() != ApiStatus.SUCCESS) {
                    ToastUtil.showToast(StringUtil.getString(R.string.item_no_no_record, itemNo));
                    return;
                }
                ItemNoStore data = apiResultData.getData();
                if (data == null) {
                    ToastUtil.showToast(StringUtil.getString(R.string.item_no_no_record, itemNo));
                    return;
                }
                addListValue(data);
            }

            @Override
            public void onFails(Exception e) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                ToastUtil.showToast(R.string.network_error);
            }
        }, new TypeToken<ApiResultData<ItemNoStore>>() {
        }.getType());
    }

    public void savePmn(Pmn pmn) {
        if (getView() != null) {
            getView().showLoading();
        }
        Date date = new Date();
        String pmnId = Utils.getGuid();
        getPmnBean(pmn, pmnId, date);
        // PmnAttach
        List<PmnAttach> pmnAttaches = getPmnAttach(pmn, pmnId, date);
        // ItemNoStore
        List<ItemNoStore> itemNos = pmn.getItemNos();
        // PmnItemNo
        List<PmnItemNo> pmnItemNos = new ArrayList<>();
        // Category
        List<Category> categories = new ArrayList<>();
        if (itemNos != null && !itemNos.isEmpty()) {
            for (int i = 0; i < itemNos.size(); i++) {
                ItemNoStore itemNo = itemNos.get(i);
                itemNo.setSyncedAt(date);
                itemNo.setSyncedStatus(ApiStatus.DOWNLOAD_SUCCESS);
                itemNos.set(i, itemNo);
                PmnItemNo pmnItemNo = new PmnItemNo();
                pmnItemNo.setId(Utils.getGuid());
                pmnItemNo.setPmnId(pmnId);
                pmnItemNo.setItemNoId(itemNo.getId());
                pmnItemNo.setCreatedAt(date);
                pmnItemNo.setModifyAt(date);
                pmnItemNo.setCreatedId(Utils.getUserId());
                pmnItemNo.setModifyId(Utils.getUserId());
                pmnItemNos.add(pmnItemNo);
                categories.add(itemNo.getCategory());
            }
            pmn.setItemNos(itemNos);
        }
        mNewPmn.insertPmn(pmn, pmnAttaches, pmnItemNos, categories, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                ApiResultData<String> apiResultData = (ApiResultData<String>) apiResult;
                mResultCode.setValue(apiResultData.getStatus());
            }

            @Override
            public void onFails(Exception e) {
                if (getView() != null) {
                    getView().hideLoading();
                }
            }
        });
    }

    private List<PmnAttach> getPmnAttach(Pmn pmn, String pmnId, Date date) {
        List<PmnAttach> pmnAttaches = pmn.getImages();
        if (pmnAttaches != null && !pmnAttaches.isEmpty()) {
            for (int i = 0; i < pmnAttaches.size(); i++) {
                PmnAttach pmnAttach = pmnAttaches.get(i);
                pmnAttach.setId(Utils.getGuid());
                pmnAttach.setPmnId(pmnId);
                pmnAttach.setCreatedAt(date);
                pmnAttach.setModifyAt(date);
                pmnAttach.setCreatedId(Utils.getUserId());
                pmnAttach.setModifyId(Utils.getUserId());
                pmnAttaches.set(i, pmnAttach);
            }
        }
        return pmnAttaches;
    }

    private Pmn getPmnBean(Pmn pmn, String pmnId, Date date) {
        pmn.setId(pmnId);
        pmn.setState(1);
        pmn.setCreatedAt(date);
        pmn.setCreatedId(Utils.getUserId());
        pmn.setModifyId(Utils.getUserId());
        pmn.setModifyAt(date);
        pmn.setSyncedStatus(ApiStatus.NO_UPLOAD);
        return pmn;
    }

    public void saveItemNo(String pmnId) {
        if (getView() != null) {
            getView().showLoading();
        }
        mNewPmn.insertPmnItemNo(pmnId, mList.getValue(), new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                ApiResultData<String> apiResultData = (ApiResultData<String>) apiResult;
                mResultCode.setValue(apiResultData.getStatus());
            }

            @Override
            public void onFails(Exception e) {
                if (getView() != null) {
                    getView().hideLoading();
                }
            }
        });
    }

    public void getItemNoList(String pmnId) {
        mPmnItemNo.getPmnItemNo(pmnId, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                ApiResultData<List<ItemNoStore>> apiResultData = (ApiResultData<List<ItemNoStore>>) apiResult;
                if (apiResultData.getStatus() != ApiStatus.SUCCESS) {
                    ToastUtil.showToast(apiResultData.getMessage());
                    return;
                }
                List<ItemNoStore> data = apiResultData.getData();
                if (data == null || data.isEmpty()) {
                    return;
                }
                setListValue(data);
            }

            @Override
            public void onFails(Exception e) {
                ToastUtil.showToast(R.string.network_error);
            }
        });
    }

    /**
     * 上传Pmn
     */
    private void uploadPmn(Pmn pmn, List<PmnItemNo> pmnItemNos) {
        List<PmnWithList> pmnWithLists = new ArrayList<>();
        PmnWithList pmnWithList = new PmnWithList();
        pmnWithList.pmnAttachs = pmn.getImages();
        pmnWithList.pmnItemNos = pmnItemNos;
        pmn.setImages(null);
        pmn.setItemNos(null);
        pmnWithList.pmn = pmn;
        pmnWithLists.add(pmnWithList);
        SyncUploadUtil.getInstance().syncPmn(pmnWithLists, new OnSyncListener() {
            @Override
            public void onSuccess() {
                if (getView() != null) {
                    getView().hideLoading();
                }
                setSyncResult(ApiStatus.SUCCESS, StringUtil.getString(R.string.sync_successfully), "");
            }

            @Override
            public void onError(String data) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                setSyncResult(ApiStatus.FAIL, StringUtil.getString(R.string.sync_failed_duplicate), StringUtil.getString(R.string.failed_pro_id,data));
            }

            @Override
            public void onFails(Exception e) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                setSyncResult(ApiStatus.FAIL, StringUtil.getString(R.string.sync_failed_network), null);
            }
        });
    }

    public void syncPmn(Pmn pmn) {
        if (getView() != null) {
            getView().showLoading();
        }
        // 先将数据保存在本地数据库
        Date date = new Date();
        String pmnId = Utils.getGuid();
        getPmnBean(pmn, pmnId, date);
        // PmnAttach
        List<PmnAttach> pmnAttaches = getPmnAttach(pmn, pmnId, date);
        // ItemNoStore
        List<ItemNoStore> itemNos = pmn.getItemNos();
        // PmnItemNo
        List<PmnItemNo> pmnItemNos = new ArrayList<>();
        // Category
        List<Category> categories = new ArrayList<>();
        if (itemNos != null && !itemNos.isEmpty()) {
            for (int i = 0; i < itemNos.size(); i++) {
                ItemNoStore itemNo = itemNos.get(i);
                itemNo.setSyncedAt(date);
                itemNo.setSyncedStatus(ApiStatus.DOWNLOAD_SUCCESS);
                itemNos.set(i, itemNo);
                PmnItemNo pmnItemNo = new PmnItemNo();
                pmnItemNo.setId(Utils.getGuid());
                pmnItemNo.setPmnId(pmnId);
                pmnItemNo.setItemNoId(itemNo.getId());
                pmnItemNo.setCreatedAt(date);
                pmnItemNo.setModifyAt(date);
                pmnItemNo.setCreatedId(Utils.getUserId());
                pmnItemNo.setModifyId(Utils.getUserId());
                pmnItemNos.add(pmnItemNo);
                categories.add(itemNo.getCategory());
            }
            pmn.setItemNos(itemNos);
        }
        mNewPmn.insertPmn(pmn, pmnAttaches, pmnItemNos, categories, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                uploadPmn(pmn, pmnItemNos);
            }

            @Override
            public void onFails(Exception e) {
            }
        });
    }

    /**
     * 同步返回
     *
     * @param status 同步结果
     * @param remark 备注
     * @param tip    失败原因
     */
    private void setSyncResult(int status, String remark, String tip) {
        ResultBean bean = new ResultBean(status, remark, tip, ScannedListFragment.class.getSimpleName());
        mResult.setValue(bean);
    }
}
